import Dep from './Dep';

let wUid = 0;
/**
 * 依赖收集和更新操作的具体实现
 */
export default class Watcher {
    constructor (target, expression, callback) {
        this.id = wUid++;
        this.target = target;
        this.getter = parsePath(expression);
        this.value = this.get();
        this.callback = callback;
    }

    get () {
        Dep.target = this;
        const obj = this.target;
        let value;
        try {
            value = this.getter(obj);
        } finally {
            Dep.target = null;
        }
        return value;
    }

    updata () {
        // debugger;
        console.log('watch  updata');
        let value = this.get();
        if (value !== this.value || typeof value === 'object') {
            const oldValue = this.value;
            this.value = value;
            this.callback.call(this.target, value, oldValue);
        }
    }
}

function parsePath (expression) {
    const pathArr = expression.split('.');
    return function (obj) {
        for (let key of pathArr) {
            if (!obj[key]) return;
            obj = obj[key];
        }
        return obj;
    };
}
